package com.example.androidthreadtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView text;
    private Button changeText;
    private static final int CHANGE_TEXT = 1;

    //这种Handler写法会造成内存泄漏
//    private Handler handler = new Handler(){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//        }
//    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case CHANGE_TEXT:
                    text.setText("Text has been changed.");
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text = findViewById(R.id.tv_text);
        changeText = findViewById(R.id.btn_change_text);
        changeText.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_change_text:
                //这里不能直接在子线程里面进行UI的更新，这会导致线程不安全
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        text.setText("Text has been changed");
//                    }
//                }).start();

                //这里使用异步消息机制来传递消息，将更新文本的消息传递到主进程中
                //这时就不存在在子线程更新UI导致的线程不安全了
                //创建Message对象，what字段保存信息，用Handler对象的sendMessage()方法将Message对象发送出去
                Message message = new Message();
                message.what = CHANGE_TEXT;
                handler.sendMessage(message);
                break;
            default:
                break;
        }
    }
}
